package com.rules.drools.service;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.rules.core.utils.CollectionUtil;
import com.rules.core.utils.ObjectUtils;
import com.rules.core.utils.Result;
import com.rules.drools.vo.fact.RuleExecutionObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DroolsExecuteService
 * @Description 执行规则service
 * @Author gz
 * @Date 2019/11/19 17:49
 * @Version 1.0
 */
@Slf4j
@Service
public class DroolsExecuteService {
    @Autowired
    private SceneInfoService sceneInfoService;
    @CreateCache(cacheType= CacheType.LOCAL,expire = 3600)
    private Cache<String,Object> cache;
    @Autowired
    private DroolsRuleEngineService droolsRuleEngineService;

    /**
     * 执行规则
     * @param params
     * @return
     */
    public Result executeDrools(Map<String,Object> params){
        Map<String,Object> req =  (Map<String,Object>)params.get("params");
        String scene = req.get("scene").toString();
        RuleExecutionObject object = new RuleExecutionObject();
        List<Map<String,Object>> list = (List<Map<String,Object>>)req.get("conList");
        if(CollectionUtil.collectionIsNull(list)){
           return Result.error("请求参数为空");
        }
        List<String> entityPkg = sceneInfoService.listEntityForScene(scene);
        for (String pkg : entityPkg) {
            System.out.println(pkg);
           try {
               Class<?> clz = Class.forName(pkg);
               Object o = ReflectUtil.newInstance(pkg);
                list.forEach(e->{
                    // 根据参数设置字段值
                    Field field = ReflectUtil.getField(clz, e.get("field").toString());
                    // 参数字段类型
                    Class<?> type = field.getType();
                    ReflectUtil.setFieldValue(o,field, ObjectUtils.getValue(e.get("fieldValue"),type));
                });
               object.addFactObject(o);
           }catch (Exception e) {
               e.printStackTrace();
           }
        }
        Map<String,Object> result = new HashMap<>();
        object.setGlobal("_result",result);
        System.out.println(object);
        RuleExecutionObject objects= droolsRuleEngineService.excute(object,scene);
        log.info("执行结果:{}",objects);
        Object str = cache.get(scene);
        if(str != null){
            objects.setRulesStr(str.toString());
        }else {
            cache.put(scene,objects.getRulesStr());
        }
        return Result.ok().put("data",objects);
    }

}
